<template>
	<view id="answer">
		<uni-nav-bar @clickLeft="handleBack" left-icon="back" fixed status-bar :shadow="true">
			<view class="nav-title">{{ setting.navTitle }}</view>
		</uni-nav-bar>
		<swiper :duration="switchDuration" :disable-touch="jumping" :circular="isCircular" :current="topicIndex" @change="onTopicChange" @animationfinish="animationfinish">
			<template v-for="(topic, index) in topicList">
				<swiper-item :key="index" v-if="topic !== null">
					<view class="swiper-item pb-30">
						<my-topic-wrong
							@next="onAutoJump"
							@finished="correctTopic(topicIndex)"
							@gotolink="gotoLink"
							:index="topic.number"
							:jumping.sync="jumping"
							:topic-index="topicIndex"
							:auto-jump="setting.autoJump"
							:correct-topic="setting.correctTopic"
							:is-correcting="setting.correcting"
							:topic="topic"
							:user-choice.sync="topic.userChoice"
							:old-user-choice.sync="topic.oldUserChoice"
							:is-recitation="setting.isRecitation"
						></my-topic-wrong>
					</view>
				</swiper-item>
			</template>
		</swiper>
		<my-answer-btm-bar
			@on-card-change="onCardChange"
			@on-collect="onCollect"
			@submit="beforeSubmit"
			@clear-history="clearHistory"
			:topic-index="topicIndex"
			:topic-list="oriTopicList"
			:topic-count="topicCount"
			:topic-number="topicList[topicIndex].number"
			:topic-info="topicInfo"
			:current-topic="currentTopic"
			:left-btn-mode="setting.leftBtnMode"
			:show-unanswered-count="setting.unansweredCount"
			:show-right-count="setting.showRightCount"
			:show-false-count="setting.showFalseCount"
			:clear-history="setting.clearHistoryHandler !== null"
			:is-fold.sync="isFold"
			:is-correcting="setting.correcting"
			:is-recitation="setting.isRecitation"
		></my-answer-btm-bar>
		<view class="modal-box" @click="isFold = true"></view>
		<!-- 答对自动跳转下一题 -->
		<uni-popup ref="popup" type="bottom">
			<view class="setting-container">
				<view class="auto-jump">
					<text>答对自动跳转下一题</text>
					<switch :checked="setting.autoJump" @change="setting.autoJump = $event.detail.value" color="#fc7767" />
				</view>
			</view>
		</uni-popup>
		<!-- beforeSubmit -->
		<my-confirm ref="beforeSubmit" @cancel="submit()" @confirm="startTimer() || $refs.beforeSubmit.close()" confirm-text="继续考试" cancel-text="现在交卷">
			当前还有
			<text class="textOrg">{{ this.totalTopicCount - this.answeredCount }}</text>
			题未做
		</my-confirm>
		<!-- clearHistory -->
		<my-confirm ref="headBack" @cancel="backCancel()" @confirm="back()" confirm-text="确定" cancel-text="取消">您确定退出考试吗？</my-confirm>
		<view v-if="modalShow" class="modal"><image class="homeOne" @click="noviceClick" src="../../static/Novice/answer.png"></image></view>
	</view>
</template>
<script>
import noLeftSlip from '../../mixins/noLeftSlip.js';
import exam from '../../mixins/exam.js';
export default {
	mixins: [noLeftSlip, exam],
	onPageScroll(e) {
		//根据距离顶部距离是否显示回到顶部按钮
		if (e.scrollTop > 100) {
			//当距离大于600时显示回到顶部按钮
			console.log(e);
		} else {
			//当距离小于600时隐藏回到顶部按钮
			this.isShow = false;
		}
	},
	onLoad(option) {
		//初始化页面配置1
		this.init(JSON.parse(option.setting));
		//获取题目列表
		const { ques, appSingMultTrueCountVO } = uni.getStorageSync('topicListWrong');
		this.oriTopicList = ques;
		this.topicInfo = appSingMultTrueCountVO;
		this.onCardChange(this.setting.topicNumber || 1);
		this.topicCount.right = this.setting.correctCount;
		this.topicCount.false = this.setting.errorCount;
		//app 后台监听
		uni.$on('app-show', () => {
			// 倒计时
			this.startTimer();
		});
		uni.$on('app-hide', () => {
			// 倒计时
			this.stopTimer();
			this.updateHistoryHander(this.currentTopic, 'change');
		});
		this.isNoviceData = JSON.parse(uni.getStorageSync('isNovice'));
		if (!this.isNoviceData.answer) {
			this.modalShow = uni.getStorageSync('isFirstOpen');
		}
	},
	data() {
		return {
			//答题页配置项
			setting: {
				navTitle: '', //导航栏标题
				isRecitation: true, //背题模式
				// 返回处理
				backHandler: null, //点击back 需要做的处理 对应为相应的处理函数名
				initArguments: [], //返回时，执行相应页面的init function 参数
				// 倒计时
				countDown: false, //倒计时
				isCountDown: true, //是否为倒计时
				timestamp: 0, //倒计时秒数
				totalSeconds: 0, //总时间
				//答题控制
				autoJump: null, //答对自动跳转下一题 null关闭该功能，true | false
				correcting: false, //题目自动批改
				topicNumber: null, //起始题号
				//题目数量控制
				showUnansweredCount: false, //显示未答的数量
				showRightCount: true, //显示答对数量
				showFalseCount: true, //显示错题数量
				errorCount: 0, //答对数量
				correctCount: 0, //答错数量
				//底部样式控制
				leftBtnMode: 'collect', //[collect 收藏按钮,submit 提交按钮,其他 交卷按钮]
				clearHistoryHandler: null, //清空答题记录处理
				correctTopic: false, //纠错题目功能
				//答题记录控制
				updateHistoryHandler: null, //更新答题记录 [addExerciseHistory,updateRecitationHistory,updateExamHistory,updateWrongOrCollectTopic]
				updateTiming: 'animationfinish', //更新答题记录的时机，在swiper animationfinish或change 事件中
				//成绩页参数
				achievementPageReload: true, //成绩页返回reload参数
				achievementPageReexamHander: null //成绩页重考处理
			},
			topicIndex: 0, //当前swiper下标【0 1 2】
			topicList: [], //当前展示题目列表
			oldTopicIndex: 0,
			oriTopicList: [], //题目原数组
			switchDuration: 200,
			isCircular: false, //是否可以进行循环滚动
			jumping: false, //是否再跳转中
			topicCount: {
				right: 0,
				false: 0
			},
			isFold: true, //底部折叠
			rightTopicIds: null, //答对题目的ids
			modalShow: false, //新手指引
			isNoviceData: {}
		};
	},
	computed: {
		currentTopic() {
			return this.topicList[this.topicIndex];
		},
		topicNumber() {
			return this.topicList[this.topicIndex].number;
		},
		totalTopicCount() {
			return this.oriTopicList.length;
		},
		isDivideByThree() {
			return this.totalTopicCount % 3 === 0;
		},
		topicOverflowCount() {
			return this.totalTopicCount % 3;
		},
		isLoadedOverflowTopic() {
			return this.topicList.length === this.topicOverflowCount + 3;
		},
		answeredCount() {
			return this.oriTopicList.filter(topic => topic.userChoice).length;
		}
	},
	watch: {
		topicIndex(n, o) {
			this.oldTopicIndex = o;
		}
	},
	methods: {
		init(setting) {
			Object.keys(setting).map(key => (this.setting[key] = setting[key]));
		},
		noviceClick() {
			// 新手指导
			this.modalShow = false;
			this.isNoviceData.answer = true;
			uni.setStorageSync('isNovice', JSON.stringify(this.isNoviceData));
		},
		resetBasicSetting() {
			this.setting.errorCount = 0;
			this.setting.correctCount = 0;
			this.setting.topicNumber = 1;
		},
		onAutoJump() {
			if (this.isCircular || this.topicNumber !== this.totalTopicCount) {
				this.topicIndex = this.calculateTopicIndex(this.topicIndex + 1);
			}
		},
		// 纠错
		gotoLink(e) {
			uni.navigateTo({
				url: `../studentWrongtopic/errorRecovery?queId=${e}`
			});
		},
		beforeSubmit() {
			//提交试卷前
			this.stopTimer();
			const { right, false: fail } = this.topicCount;
			if (this.answeredCount < this.totalTopicCount) this.$refs.beforeSubmit.open();
			else this.submit();
		},
		onTopicChange(e) {
			// //第一张自动跳转问题修复
			this.updateHistoryHander(this.currentTopic, 'change');
			this.topicIndex = e.detail.current;
			this.jumping = true;
			const timer = setTimeout(() => {
				this.jumping = false;
			}, 500);
		},
		onCardChange(topicNumber) {
			//点击答题卡跳转
			if (this.oriTopicList.length <= 3) {
				//题目数量小于3
				this.topicList.length || (this.topicList = this.oriTopicList);
				this.changeTopicIndex(topicNumber - 1);
				return;
			}
			const index = topicNumber - 1;
			if (index === 0) {
				//点击第一题
				this.topicList = this.getTopic(index);
				this.changeTopicIndex(0);
				return;
			}

			if (index === this.oriTopicList.length - 1 && this.isDivideByThree) {
				//点击最后一题
				this.topicList = this.getTopic(index);
				this.changeTopicIndex(2);
				return;
			}
			if (!this.isDivideByThree && this.isTopicNumberInOverflow(topicNumber)) {
				//点击取余3超出的部分
				let startIndex = this.totalTopicCount - this.topicOverflowCount - 3;
				this.topicList = this.oriTopicList.slice(startIndex);
				this.changeTopicIndex(2 + (topicNumber % 3));
				return;
			}
			//正常跳转
			let [pre] = this.getTopic(index - 1, 1);
			let [cur] = this.getTopic(index, 1);
			let [next] = this.getTopic(index + 1, 1);
			switch (topicNumber % 3) {
				case 0:
					this.topicList = [next, pre, cur];
					this.changeTopicIndex(2);
					break;
				case 2:
					this.topicList = [pre, cur, next];
					this.changeTopicIndex(1);
					break;
				default:
					this.topicList = [cur, next, pre];
					this.changeTopicIndex(0);
					break;
			}
		},
		onCollect(topic) {
			const { chapterId = null, colqueid, paperId = null, queId, collect, examId } = topic;
			this.request.post('/app/collect/addAndDeleteCollect', { chapterId, colqueid, paperId, queId, collect, examId }).then(res => {
				topic.collect = res;
			});
		},
		getMoveDirection(from, to) {
			if ((to === 0 && from === 2) || (to - from !== 2 && to > from)) return 'left';
			else return 'right';
		},
		animationfinish(e) {
			const index = e.detail.current;
			//判断当前题目是否为第一个或者最后一个
			this.isCircular = this.getIsCircular();
			this.correctTopic(this.oldTopicIndex, true);
			const moveDirection = this.getMoveDirection(this.oldTopicIndex, index);
			const realTopicNumber = this.currentTopic.number;
			if (!this.isCircular) return;

			if (moveDirection === 'left' && realTopicNumber > 2) {
				if (!this.isDivideByThree && this.isTopicNumberInOverflow(realTopicNumber) && !this.isLoadedOverflowTopic) {
					this.topicList.push(this.oriTopicList[realTopicNumber]);
				}
				if (this.topicList.length === 3) {
					let spliceIndex = this.calculateTopicIndex(this.topicIndex + 1);
					// console.log('左滑 加载');
					this.topicList.splice(spliceIndex, 1, this.oriTopicList[realTopicNumber]);
				}
			}

			if (moveDirection === 'right' && realTopicNumber !== 1) {
				if (this.topicList.length === 3) {
					// console.log('右滑 返回');
					let spliceIndex = this.calculateTopicIndex(this.topicIndex - 1);
					this.topicList.splice(spliceIndex, 1, this.oriTopicList[realTopicNumber - 2]);
				}
				if (this.topicIndex === 1 && this.topicList.length > 3) {
					this.topicList.splice(3, this.topicList.length);
				}
			}
		},
		calculateTopicIndex(newTopicIndex) {
			//topic index 临界值处理
			if (newTopicIndex === 3) return 0;
			if (newTopicIndex === -1) return 2;
			return newTopicIndex;
		},
		correctTopic(index, isSlipped = false) {
			const { updateHistoryHandler } = this.setting;
			if (this.setting.isRecitation) {
				this[updateHistoryHandler](this.topicList[index], 'animationfinish');
				return;
			}
			const { userChoice, rightAnswer, isCorrect, number: topicNumber, historyId } = this.topicList[index];
			let correctRes;
			//批改题目
			// console.log(isSlipped);
			// console.log('批改题目');
			if (userChoice && (isCorrect === null || !this.correcting)) {
				correctRes = userChoice === rightAnswer;
				if (isCorrect === null) {
					if (correctRes) this.topicCount.right++;
					else this.topicCount.false++;
				}
				this.oriTopicList[topicNumber - 1].isCorrect = correctRes;
				this.updateHistoryHander(this.topicList[index], 'animationfinish');
				setTimeout(() => {
					this.$set(this.oriTopicList[topicNumber - 1], 'isSlipped', true);
				}, 1000);
			}
		},
		updateHistoryHander(topic, timing) {
			//更新答题钩子
			const { updateTiming, updateHistoryHandler } = this.setting;
			const { number, userChoice, oldUserChoice } = topic;
			if (userChoice === null || userChoice === oldUserChoice) return Promise.resolve();
			if (timing === updateTiming && updateHistoryHandler) {
				this.$nextTick(function() {
					topic.oldUserChoice = userChoice;
				});
				return this[updateHistoryHandler](topic);
			}
		},
		addExerciseHistory(topic) {
			//练习添加练习记录
			this.request.post('/app/exercise/addAnswerHistory', topic);
		},
		updateRecitationHistory(topic) {
			//更新背题记录\
			this.debounce(() => {
				const { chapterId, number, queId } = topic;
				this.request.post('/app/teacher/home/reciteQuestion', {
					chapterid: chapterId,
					number,
					queid: queId,
					type: 7,
					examid: Number(this.setting.examid)
				});
			});
		},
		updateExamHistory(topic) {
			//考试更新答题记录
			// console.log('更新试题记录\n', topic);
			const { historyId, userChoice, rightAnswer, number } = topic;
			const duration = this.getUsedTime();
			const isCorrect = rightAnswer === userChoice;
			return new Promise((resolve, reject) => {
				this.request
					.post('/app/exam/updateAnswerHistory', {
						historyId,
						isCorrect,
						userChoice,
						duration,
						number
					})
					.then(resolve)
					.catch(reject);
			});
		},
		getTopic(index, count = 3) {
			const offset = (count - 1) / 2;
			//点击第一题与最后一题进行特殊处理
			if (index === 0) return this.oriTopicList.slice(index, count);
			if (index === this.oriTopicList.length - 1) return this.oriTopicList.slice(this.oriTopicList.length - count, this.oriTopicList.length);
			return this.oriTopicList.slice(index - offset, index + offset + 1);
		},
		clearHistory() {
			// 清除答题弹窗显示
			this.isFold = true;
			this.$refs.clearHistory.open();
		},
		changeTopicIndex(target) {
			this.switchDuration = 0;
			this.topicIndex = target;
			this.isCircular = this.getIsCircular();
			this.$nextTick(function() {
				this.switchDuration = 200;
				this.isFold = true;
			});
		},
		handleBack() {
			this.updateHistoryHander(this.currentTopic, 'change');
			if (this.setting.backHandler) this[this.setting.backHandler]();
			else this.back();
		},
		emptyRightAnswer() {
			//清除已答对的题目
			this.rightTopicIds = this.oriTopicList
				.reduce((ids, { isCorrect, colqueid }) => {
					isCorrect && ids.push(colqueid);
					return ids;
				}, [])
				.join(',');
			if (this.rightTopicIds === '') {
				this.back();
				return;
			}
			this.$nextTick(function() {
				this.$refs.emptyRightAnswer.open();
			});
		},
		backCancel() {
			this.$refs.headBack.close();
			this.startTimer();
		},
		confirmBack() {
			this.stopTimer();
			this.$nextTick(function() {
				this.$refs.headBack.open();
			});
		},
		async back() {
			//记录返回时最后一道题的答案
			await this.updateHistoryHander(this.currentTopic, this.setting.updateTiming);
			//返回 并且重新加载目标页面数据
			const pages = getCurrentPages();
			if (pages[pages.length - 2].$vm.init) pages[pages.length - 2].$vm.init(...this.setting.initArguments);
			uni.navigateBack();
		},
		getRightTopicIds() {
			return this.oriTopicList
				.reduce((ids, { isCorrect, colqueid }) => {
					isCorrect && ids.push(colqueid);
					return ids;
				}, [])
				.join(',');
		},
		getIsCircular() {
			//判断当前是否可以进行循环滚动
			return this.currentTopic.number !== 1 && this.currentTopic.number !== this.oriTopicList.length;
		},
		isTopicNumberInOverflow(topicNumber) {
			//当题目不是3的倍数时，点击的部分是否为超出的部分
			return this.totalTopicCount - topicNumber <= this.topicOverflowCount;
		},
		startTimer() {
			//定时器启动
			this.$refs.timer && this.$refs.timer.start();
		},
		stopTimer() {
			//定时器暂停
			this.$refs.timer && this.$refs.timer.stop();
		},
		timerSeconds() {
			//获取定时器剩余时间
			return (this.$refs.timer && this.$refs.timer.seconds) || null;
		},
		getUsedTime() {
			//获取用户耗时
			//正计时直接获取timer 时间
			if (!this.setting.isCountDown) return this.timerSeconds();
			//倒计时计算耗时
			return this.setting.totalSeconds - this.timerSeconds();
		}
	}
};
</script>
<style>
page {
	background-color: #ffffff;
}
</style>

<style scoped lang="scss">
	.navbarShadow{
		box-shadow: 2upx 2upx 15upx rgba(0, 0, 0, 0.06);
	}
/deep/ .uni-navbar--border {
	border: none !important;
}
/deep/ .uni-navbar__header-btns {
	width: 150upx;
}
.modal {
	display: flex;
	justify-content: center;
	align-items: center;
	background: rgba(0, 0, 0, 0.8);
	position: fixed;
	width: 100%;
	height: 100%;
	z-index: 1000;
}
.homeOne {
	width: 426upx;
	height: 636upx;
}
.textOrg {
	color: #f45c4b;
}
.timer {
	font-size: 34upx;
	font-weight: 400;
	color: #363940;
	margin: auto;
	text {
		margin-right: 6upx;
	}
	image {
		width: 32upx;
		height: 32upx;
		margin-right: 10upx;
	}
}
.nav-title {
	text-align: center;
	width: 100%;
	font-size: 34upx;
	font-weight: 500;
	color: #363940;
}
.setting {
	width: 38upx;
	height: 38upx;
	right: -20upx;
}
#answer {
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
}
.swiper-item {
	padding: 50upx 30upx 0upx 30upx;
	height: calc(100% - 100upx);
	overflow-y: scroll;
}
.modal-box {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.4);
	z-index: 999;
	display: none;
}
.btm-bar--unfold + .modal-box {
	display: unset;
}
/deep/ swiper {
	display: unset !important;
	flex: 1;
}
/deep/ .uni-popup {
	z-index: 1000;
}
.setting-container {
	background-color: #ebebeb;
	padding: 30upx;
	.auto-jump {
		// border-bottom: 1px solid #ebebeb;
		display: flex;
		align-items: center;
		text {
			flex: 1;
		}
	}
}
/deep/ .uni-switch-input-checked {
	background: $linear-bg !important;
}
</style>
